package rpc

import (
	"gitee.com/tietang/terrace-go/v2/lib/rpc/mo/entity"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/models"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/seri"
)

type Handler interface {
	Handle(msg *models.RpcMessage[any]) (*entity.ResEntity, error)
	Unmarshal(data []byte, seri seri.Serialization) (any, error)
}

var _ Handler = new(MessageHandler)

func NewHandler(fn func(msg *models.RpcMessage[any]) (res *entity.ResEntity, err error)) Handler {
	return &MessageHandler{
		fn: fn,
	}
}

type MessageHandler struct {
	fn func(msg *models.RpcMessage[any]) (res *entity.ResEntity, err error)
}

func (d *MessageHandler) Handle(msg *models.RpcMessage[any]) (res *entity.ResEntity, err error) {
	return d.fn(msg)
}

func (d *MessageHandler) Unmarshal(data []byte, seri seri.Serialization) (any, error) {
	v := make(map[string]interface{})
	err := seri.From(data, &v)
	return v, err
}
